import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;

public class StudentMainFrame extends JFrame {
    private User currentUser;
    private JTable examTable;
    private DefaultTableModel tableModel;
    private JComboBox<String> statusFilterCombo;
    private JButton enterExamButton;
    private JButton viewScoreButton;
    private JButton refreshButton;
    private JButton logoutButton;
    private ExamDAO examDAO;
    private ExamRecordDAO examRecordDAO;

    // 存储所有考试数据用于筛选
    private List<ExamDisplayData> allExamData;

    public StudentMainFrame(User user) {
        this.currentUser = user;
        this.examDAO = new ExamDAO();
        this.examRecordDAO = new ExamRecordDAO();
        this.allExamData = new ArrayList<>();
        initComponents();
        setupLayout();
        setupEvents();
        loadExamList();
    }

    private void initComponents() {
        setTitle("在线考试系统 - 学生端 (" + currentUser.getRealName() + ")");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1200, 750);
        setLocationRelativeTo(null);
        setResizable(true);

        // 表格列名
        String[] columnNames = { "考试ID", "考试名称", "开始时间", "结束时间", "时长(分钟)", "总分", "状态", "我的成绩" };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        examTable = new JTable(tableModel);
        examTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        examTable.setRowHeight(35);
        examTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));

        // 设置表格列宽
        examTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        examTable.getColumnModel().getColumn(1).setPreferredWidth(280);
        examTable.getColumnModel().getColumn(2).setPreferredWidth(150);
        examTable.getColumnModel().getColumn(3).setPreferredWidth(150);
        examTable.getColumnModel().getColumn(4).setPreferredWidth(100);
        examTable.getColumnModel().getColumn(5).setPreferredWidth(80);
        examTable.getColumnModel().getColumn(6).setPreferredWidth(100);
        examTable.getColumnModel().getColumn(7).setPreferredWidth(100);

        // 设置表头
        examTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 16));
        examTable.getTableHeader().setPreferredSize(new Dimension(0, 40));

        // 状态筛选下拉框
        String[] filterOptions = { "全部考试", "未开始", "可作答", "已作答", "已结束" };
        statusFilterCombo = new JComboBox<>(filterOptions);
        statusFilterCombo.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        statusFilterCombo.setPreferredSize(new Dimension(120, 35));

        // 按钮
        Dimension buttonSize = new Dimension(120, 45);
        Font buttonFont = new Font("微软雅黑", Font.BOLD, 16);

        enterExamButton = new JButton("进入考试");
        enterExamButton.setPreferredSize(buttonSize);
        enterExamButton.setFont(buttonFont);
        enterExamButton.setBackground(new Color(40, 167, 69));
        enterExamButton.setForeground(Color.WHITE);

        viewScoreButton = new JButton("查看成绩");
        viewScoreButton.setPreferredSize(buttonSize);
        viewScoreButton.setFont(buttonFont);
        viewScoreButton.setBackground(new Color(70, 130, 180));
        viewScoreButton.setForeground(Color.WHITE);

        refreshButton = new JButton("刷新");
        refreshButton.setPreferredSize(buttonSize);
        refreshButton.setFont(buttonFont);
        refreshButton.setBackground(new Color(108, 117, 125));
        refreshButton.setForeground(Color.WHITE);

        logoutButton = new JButton("退出登录");
        logoutButton.setPreferredSize(new Dimension(100, 35));
        logoutButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        logoutButton.setBackground(new Color(220, 53, 69));
        logoutButton.setForeground(Color.WHITE);
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));

        // 顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(new Color(70, 130, 180));
        topPanel.setPreferredSize(new Dimension(1200, 80));

        JLabel titleLabel = new JLabel("全部考试", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(Color.WHITE);

        JPanel userPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 15, 20));
        userPanel.setBackground(new Color(70, 130, 180));
        JLabel userLabel = new JLabel("欢迎，" + currentUser.getRealName());
        userLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        userLabel.setForeground(Color.WHITE);
        userPanel.add(userLabel);
        userPanel.add(logoutButton);

        topPanel.add(titleLabel, BorderLayout.CENTER);
        topPanel.add(userPanel, BorderLayout.EAST);

        // 筛选面板
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 10));
        filterPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));

        JLabel filterLabel = new JLabel("筛选条件:");
        filterLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        filterLabel.setForeground(new Color(70, 130, 180));

        filterPanel.add(filterLabel);
        filterPanel.add(statusFilterCombo);

        // 中间表格面板
        JScrollPane scrollPane = new JScrollPane(examTable);
        scrollPane.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                "考试列表",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(70, 130, 180)));

        // 主内容面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        mainPanel.add(filterPanel, BorderLayout.NORTH);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 25, 20));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 0, 15, 0));
        buttonPanel.add(enterExamButton);
        buttonPanel.add(viewScoreButton);
        buttonPanel.add(refreshButton);

        add(topPanel, BorderLayout.NORTH);
        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void setupEvents() {
        statusFilterCombo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                filterExamList();
            }
        });

        enterExamButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                enterExam();
            }
        });

        viewScoreButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                viewScore();
            }
        });

        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loadExamList();
            }
        });

        logoutButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                logout();
            }
        });

        // 双击进入考试
        examTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) {
                    enterExam();
                }
            }
        });
    }

    private void loadExamList() {
        allExamData.clear();
        List<Exam> exams = examDAO.getAllExamsForStudent();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        for (Exam exam : exams) {
            // 获取学生的考试记录
            ExamRecord record = examRecordDAO.getExamRecord(exam.getId(), currentUser.getId());
            String status = getExamStatus(exam, record);
            String score = getScoreDisplay(record);

            ExamDisplayData data = new ExamDisplayData(
                    exam.getId(),
                    exam.getTitle(),
                    sdf.format(exam.getStartTime()),
                    sdf.format(exam.getEndTime()),
                    exam.getDuration(),
                    exam.getTotalScore(),
                    status,
                    score,
                    exam,
                    record);
            allExamData.add(data);
        }

        // 应用当前筛选
        filterExamList();
    }

    private void filterExamList() {
        tableModel.setRowCount(0);
        String selectedFilter = (String) statusFilterCombo.getSelectedItem();

        for (ExamDisplayData data : allExamData) {
            boolean shouldShow = false;

            switch (selectedFilter) {
                case "全部考试":
                    shouldShow = true;
                    break;
                case "未开始":
                    shouldShow = "未开始".equals(data.status);
                    break;
                case "可作答":
                    shouldShow = "可作答".equals(data.status);
                    break;
                case "已作答":
                    shouldShow = "已作答".equals(data.status) || "已阅卷".equals(data.status);
                    break;
                case "已结束":
                    shouldShow = "已结束".equals(data.status);
                    break;
            }

            if (shouldShow) {
                Object[] row = {
                        data.examId,
                        data.title,
                        data.startTime,
                        data.endTime,
                        data.duration,
                        data.totalScore,
                        data.status,
                        data.score
                };
                tableModel.addRow(row);
            }
        }
    }

    private String getExamStatus(Exam exam, ExamRecord record) {
        long now = System.currentTimeMillis();
        long startTime = exam.getStartTime().getTime();
        long endTime = exam.getEndTime().getTime();

        // 首先检查考试时间范围
        if (now < startTime) {
            return "未开始";
        } else if (now > endTime) {
            // 考试已结束
            if (record != null && ("submitted".equals(record.getStatus()) || "graded".equals(record.getStatus()))) {
                return "已阅卷".equals(record.getStatus()) ? "已阅卷" : "已作答";
            } else {
                return "已结束"; // 考试结束但未作答
            }
        } else {
            // 考试进行中
            if (record != null) {
                if ("submitted".equals(record.getStatus()) || "graded".equals(record.getStatus())) {
                    return "已阅卷".equals(record.getStatus()) ? "已阅卷" : "已作答";
                } else if ("in_progress".equals(record.getStatus())) {
                    return "考试中";
                }
            }
            return "可作答"; // 考试时间内且未开始作答
        }
    }

    private String getScoreDisplay(ExamRecord record) {
        if (record != null && "graded".equals(record.getStatus())) {
            return String.valueOf(record.getTotalScore());
        } else if (record != null && "submitted".equals(record.getStatus())) {
            return "阅卷中";
        }
        return "未参加";
    }

    private void enterExam() {
        int selectedRow = examTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一个考试！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int examId = (Integer) tableModel.getValueAt(selectedRow, 0);
        String status = (String) tableModel.getValueAt(selectedRow, 6);

        if ("已作答".equals(status) || "已阅卷".equals(status)) {
            JOptionPane.showMessageDialog(this, "您已经完成了这个考试！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if ("未开始".equals(status)) {
            JOptionPane.showMessageDialog(this, "考试还未开始！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if ("已结束".equals(status)) {
            JOptionPane.showMessageDialog(this, "考试已经结束！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 显示考试确认对话框
        Exam exam = examDAO.getExamById(examId);
        if (exam != null) {
            new ExamConfirmDialog(this, exam, currentUser).setVisible(true);
        }
    }

    private void viewScore() {
        int selectedRow = examTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一个考试！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int examId = (Integer) tableModel.getValueAt(selectedRow, 0);
        ExamRecord record = examRecordDAO.getExamRecord(examId, currentUser.getId());

        if (record == null || (!"graded".equals(record.getStatus()) && !"submitted".equals(record.getStatus()))) {
            JOptionPane.showMessageDialog(this, "该考试还没有成绩或未参加！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        new ScoreViewFrame(examId, currentUser.getId()).setVisible(true);
    }

    private void logout() {
        int result = JOptionPane.showConfirmDialog(this, "确定要退出登录吗？", "确认", JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            new LoginFrame().setVisible(true);
            this.dispose();
        }
    }

    // 内部类用于存储考试显示数据
    private static class ExamDisplayData {
        int examId;
        String title;
        String startTime;
        String endTime;
        int duration;
        double totalScore;
        String status;
        String score;
        Exam exam;
        ExamRecord record;

        public ExamDisplayData(int examId, String title, String startTime, String endTime,
                int duration, double totalScore, String status, String score,
                Exam exam, ExamRecord record) {
            this.examId = examId;
            this.title = title;
            this.startTime = startTime;
            this.endTime = endTime;
            this.duration = duration;
            this.totalScore = totalScore;
            this.status = status;
            this.score = score;
            this.exam = exam;
            this.record = record;
        }
    }

    // 公共方法供其他界面调用刷新
    public void refreshExamList() {
        loadExamList();
    }
}